# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login, logout
from django.contrib.auth.models import Group
from django.contrib import messages
from .. import views
from django.utils.translation import gettext as _

# Helper function to check if user is in a specific group


def is_admin(user):
    return user.is_superuser


def is_regular_user(user):
    # Treat users with no group as regular
    return user.groups.filter(name='Regular User').exists() or not user.groups.exists()


# 自定义UserCreationForm，提供中文错误信息
class ChineseUserCreationForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 自定义错误消息
        self.error_messages.update({
            'password_mismatch': '两次输入的密码不匹配',
            'password_too_short': '密码长度不足',
            'password_too_similar': '密码与用户名太相似',
            'password_too_common': '密码太常见',
            'password_entirely_numeric': '密码不能全是数字',
        })

        # 覆盖默认的help_text
        self.fields['username'].help_text = '150个字符以内。只能用字母、数字和@/./+/-/_'
        self.fields['password1'].help_text = '密码必须至少有6个字符，或者是6位数字。'
        self.fields['password2'].help_text = '请输入与上面相同的密码，以进行验证。'


def signup_view(request):
    if request.method == 'POST':
        form = ChineseUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            # Add user to the 'Regular User' group
            try:
                group = Group.objects.get(name='Regular User')
            except Group.DoesNotExist:
                # Create the group if it doesn't exist
                group = Group.objects.create(name='Regular User')

            user.groups.add(group)
            login(request, user)
            return redirect('/')
    else:
        form = ChineseUserCreationForm()
    return render(request, 'auth/signup.html', {'form': form})


def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            if is_admin(user):
                return redirect('user_manage')
            else:
                return redirect('home')
        else:
            # 添加自定义错误信息
            if 'username' in form.errors:
                form.errors['username'] = ['用户名不存在']
            if 'password' in form.errors:
                form.errors['password'] = ['密码错误']
            if '__all__' in form.errors:
                form.errors['__all__'] = ['用户名或密码错误']
    else:
        form = AuthenticationForm()
    return render(request, 'auth/login.html', {'form': form})


def logout_view(request):
    logout(request)
    return redirect('/login/')
